package com.sugar.real.estate.module.business.service.config;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sugar.real.estate.framework.common.pojo.PageResult;
import com.sugar.real.estate.framework.common.util.object.BeanUtils;
import com.sugar.real.estate.module.business.controller.admin.config.vo.BizConfigPageReqVO;
import com.sugar.real.estate.module.business.controller.admin.config.vo.BizConfigSaveReqVO;
import com.sugar.real.estate.module.business.controller.app.config.vo.AppBasicConfigRespVO;
import com.sugar.real.estate.module.business.dal.dataobject.config.BizConfigDO;
import com.sugar.real.estate.module.business.dal.mysql.config.BizConfigMapper;
import com.sugar.real.estate.module.business.enums.config.ConfigEnum;
import com.sugar.real.estate.module.business.util.I18nUtil;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.sugar.real.estate.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.real.estate.module.business.enums.ErrorCodeConstants.BIZ_CONFIG_NOT_EXISTS;
import static com.sugar.real.estate.module.business.enums.config.ConfigEnum.*;

/**
 * 参数配置 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class BizConfigServiceImpl implements BizConfigService {

    @Resource
    private BizConfigMapper bizConfigMapper;

    @Override
    public void updateBizConfig(BizConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateBizConfigExists(updateReqVO.getId());
        // 更新
        BizConfigDO updateObj = BeanUtils.toBean(updateReqVO, BizConfigDO.class, o -> {
            if (HOME_TOP_BANNER.getValue().equals(o.getConfigKey()) || HOME_MIDDLE_BANNER.getValue().equals(o.getConfigKey())) {
                o.setValue(String.join(",", (List<String>) updateReqVO.getValue()));
            } else
                o.setValue(String.valueOf(updateReqVO.getValue()));
        });
        bizConfigMapper.updateById(updateObj);
    }

    private void validateBizConfigExists(Long id) {
        if (bizConfigMapper.selectById(id) == null) {
            throw exception(BIZ_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public BizConfigDO getBizConfig(Long id) {
        return bizConfigMapper.selectById(id);
    }

    @Override
    public PageResult<BizConfigDO> getBizConfigPage(BizConfigPageReqVO pageReqVO) {
        return bizConfigMapper.selectPage(pageReqVO);
    }

    // ======================================== 其它 接口 ========================================

    @Override
    public <T> T getBizConfigByKey(ConfigEnum configEnum, Class<T> cls) {
        BizConfigDO config = bizConfigMapper.selectOne(BizConfigDO::getConfigKey, configEnum.getValue());
        if (Objects.isNull(config))
            throw exception(BIZ_CONFIG_NOT_EXISTS, I18nUtil.getMessage("BIZ_CONFIG_NOT_EXISTS"));

        return cn.hutool.core.convert.Convert.convert(cls, config.getValue());
    }

    @Override
    public <K, T> Map<K, T> getBizConfigMapByKeys(Class<K> kCls, Class<T> cls, ConfigEnum... configEnums) {
        List<BizConfigDO> bizConfigs = bizConfigMapper.selectList(Wrappers.<BizConfigDO>lambdaQuery()
                .in(BizConfigDO::getConfigKey, Arrays.stream(configEnums).map(ConfigEnum::getValue).collect(Collectors.toList())));
        return bizConfigs
                .stream()
                .collect(Collectors
                        .groupingBy(o -> kCls.equals(ConfigEnum.class) ? kCls.cast(ConfigEnum.find(o.getConfigKey())) : kCls.cast(o.getConfigKey()),
                                Collectors.mapping(BizConfigDO::getValue,
                                        Collectors.collectingAndThen(Collectors.toList(),
                                                list -> list.isEmpty() ? null : cn.hutool.core.convert.Convert.convert(cls, list.get(0))))));
    }

    // ======================================== APP 接口 ========================================

    @Override
    public AppBasicConfigRespVO getBizConfigBasic() {
        Map<ConfigEnum, String> configMap = this.getBizConfigMapByKeys(ConfigEnum.class, String.class,
                PROJECT_NAME_ZH_CN,
                PROJECT_NAME_EN_US,
                PROJECT_LOGO,
                USER_PRIVACY_AGREEMENT_ZH_CN,
                USER_PRIVACY_AGREEMENT_EN_US,
                HOME_TOP_BANNER,
                HOME_MIDDLE_BANNER);

        AppBasicConfigRespVO respVO = new AppBasicConfigRespVO();

        respVO.setLogo(configMap.get(PROJECT_LOGO));
        respVO.setName(configMap.get(I18nUtil.getConfigEnumVal("project_name")));
        respVO.setUserPrivacyAgreement(configMap.get(I18nUtil.getConfigEnumVal("user_privacy_agreement")));
        respVO.setHomeTopBanner(configMap.get(HOME_TOP_BANNER).split(","));
        respVO.setHomeMiddleBanner(configMap.get(HOME_MIDDLE_BANNER).split(","));

        return respVO;
    }
}